﻿using System;
using System.Collections.Generic;
using System.Linq;
using Shell.DomainDot;
using Framework.Poco;

namespace Framework.Domain
{
    /// <summary>
    /// 经销商分组下的广告
    /// </summary>
    public class CategoryAdvertisingContext : DomainDotBase<Category>
    {
        /// <summary>
        /// 属于经销商分组下的广告链接
        /// </summary>
        public WithMany<Advertising> Advertisings { private get; set; }

        /// <summary>
        /// 获取所有经销商分组下的广告链接
        /// </summary>
        public IEnumerable<Advertising> GetAdvertisings()
        {
            return this.Advertisings;
        }

        /// <summary>
        /// 广告创建
        /// </summary>
        public void Create(Advertising advertising)
        {
            advertising.Created = DateTime.Now;
            advertising.Name = this.Instance.Name;
            var entity = this.Advertisings.Create();
            PocoUtils.AssignProperty<Advertising>(advertising, entity, typeof(Guid));
            this.Advertisings.Submit();
        }

        /// <summary>
        /// 广告创建
        /// </summary>
        public void Create(Advertising advertising, Guid pictureId)
        {
            advertising.Created = DateTime.Now;
            advertising.Name = this.Instance.Name;
            var entity = this.Advertisings.Create();
            PocoUtils.AssignProperty<Advertising>(advertising, entity, typeof(Guid));
            this.Advertisings.Submit();
            var context = DomainDotFactory.Factory.Create<AdvertisingAndPictureContext>(entity.Id);
            context.BindBinaryFile(pictureId);
        }

        /// <summary>
        /// 广告删除
        /// </summary>
        public void Delete(Guid identity)
        {
            var original = this.GetAdvertisings().SingleOrDefault(o => o.Id == identity);
            if (original != null)
            {
                var context = DomainDotFactory.Factory.Create<AdvertisingAndPictureContext>(original.Id);
                context.Delete();
                this.Advertisings.Delete(original.Id);
                this.Advertisings.Submit();
            }
        }
    }
}
